package com.billing.web.controller.crm;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.billing.config.ServiceConfig;
import com.billing.model.entity.CrmContact;
import com.billing.model.entity.CrmCustomer;
import com.billing.model.entity.CrmLinkman;
import com.billing.model.entity.CrmUserUploadCard;
import com.billing.model.entity.TUser;
import com.billing.service.CrmService;
import com.billing.service.ManagerPermissionsService;
import com.billing.service.UserService;
import com.billing.utils.CardApiUtil;
import com.billing.utils.ExcelUtil;

/**
 * crm
 * @author pc
 *
 */

@RequestMapping(value = "crm")
@Controller
public class CrmController {
	@Resource
	private CrmService crmService;
	@Resource
	private UserService userService;
	@Resource
	private ManagerPermissionsService managerService;
	
	SimpleDateFormat mdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat formatym = new SimpleDateFormat("yyyy-MM");
	
	/**
	 * 获取客户信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "index",method = RequestMethod.GET)
	public String index(HttpServletRequest request,Model model){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");
		String name = request.getParameter("name");
		String type = request.getParameter("type");

		boolean mp = managerService.selectPermissionsByCode(userid,"export");
		if (mp) {
			request.setAttribute("Code","export");
		}
		int pageSize = 10;
		try {
			if (name!=null&&name.length() > 0) {
				name = URLDecoder.decode(URLDecoder.decode(name, "UTF-8"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		request.setAttribute("name", name);
		request.setAttribute("type", type);
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		Map<String, Object> map = null;
		boolean mpermissions = managerService.selectPermissionsByCode(userid,"allCustomer");
		if (mpermissions) {
			 map = crmService.selectAllCustomer(userid, name,type, pageSize, currentPage);
		}else{
			 map = crmService.getCustomerPage(userid+"", name,type, pageSize, currentPage);
		}
		request.setAttribute("list", map.get("list"));//list
		request.setAttribute("currentPage", currentPage);//currentPage
        request.setAttribute("totalNum", map.get("totalNum"));//totalNum
        request.setAttribute("totalPage", map.get("totalPage"));//totalPage
		return "crm/index";
	}
	/**
	 * 新增或修改客户页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addCustomerMain",method = RequestMethod.GET)
	public String addCustomerMain(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		CrmCustomer customer = new CrmCustomer();
		if(id != null && !id.equals("")){
			customer = crmService.getCustomerById(id);
		}
		request.setAttribute("customerid", id);
		request.setAttribute("cus", customer);
		return "crm/addCustomer";
	}
	/**
	 * 新增或修改客户
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "save",method = RequestMethod.POST)
	@ResponseBody
	public String saveCustomer(HttpServletRequest request,Model model,CrmCustomer customer,CrmLinkman linkman){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");
		Integer id = customer.getId();
		if(id != null){//修改操作
			try {
				//客户名是否存在
				if(crmService.customerIsNameExist(customer.getCustName(), userid+"", id)){
					return "custNameExist";
				}
				//客户是否封档
				if(crmService.customerIsBracket(id+"")){
					return "custIsBracket";
				}
				crmService.updateCustomer(customer);
				return "updateok";
			} catch (Exception e) {
				return "updateno";
			}
		}else{//新增操作
			try {
				if(crmService.customerIsNameExist(customer.getCustName(), userid+"", null)){
					return "custNameExist";
				}
				customer.setUserId(userid);
				customer.setCreateTime(new Date().getTime());
				crmService.addCustomer(customer);
				if (linkman.getLkmSex() != null) {
					linkman.setCustId(customer.getId());
					crmService.addlinkman(linkman);
				}
				return "addok";
			} catch (Exception e) {
				e.printStackTrace();
				return "addno";
			}
		}
	}
	/**
	 * 查看客户信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="look",method = RequestMethod.GET)
	public String look(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		CrmCustomer customer = crmService.getCustomerById(id);
		request.setAttribute("cus", customer);
		return "crm/lookCustomer";
	}
	/**
	 * 查看公司联系人列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="linkmanlist",method = RequestMethod.GET)
	public String linkmanlist(HttpServletRequest request,Model model){
		String customerid = request.getParameter("id");
		String status = request.getParameter("status");
		int pageSize = 10;
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		Map<String,Object> map = crmService.getlinkmanPageByCustomerid(customerid, pageSize, currentPage);
		request.setAttribute("status", status);
		request.setAttribute("customerid", customerid);
		request.setAttribute("customerName", map.get("customerName"));
		request.setAttribute("list", map.get("list"));
		request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalNum", map.get("totalNum"));
        request.setAttribute("totalPage", map.get("totalPage"));
		return "crm/linkmanlist";
	}
	/**
	 * 新增或修改公司联系人界面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="addlinkman",method = RequestMethod.GET)
	public String addlinkman(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		String customerid = request.getParameter("customerid");
		CrmLinkman linkman = new CrmLinkman();
		if(id != null && !id.equals("")){
			linkman = crmService.getlinkmanByid(id);
		}
		request.setAttribute("linkmanid", id);
		request.setAttribute("customerid", customerid);
		request.setAttribute("lkm", linkman);
		return "crm/addLinkman";
	}
	/**
	 * 新增或修改公司联系人
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="savelinkman",method = RequestMethod.POST)
	@ResponseBody
	public String savelinkman(HttpServletRequest request,Model model,CrmLinkman linkman){
		Integer id = linkman.getId();
		Integer custId = linkman.getCustId();
		//客户是否封档
		if(crmService.customerIsBracket(custId+"")){
			return "custIsBracket";
		}
		if(id != null){//修改操作
			try {
				crmService.updatelinkman(linkman);
				return "updateok";
			} catch (Exception e) {
				return "updateno";
			}
		}else{//新增操作
			try {
				crmService.addlinkman(linkman);
				return "addok";
			} catch (Exception e) {
				return "addno";
			}
		}
	}
	/**
	 * 查看联系人信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="looklinkman",method = RequestMethod.GET)
	public String looklinkman(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		CrmLinkman linkman = crmService.getlinkmanByid(id);
		request.setAttribute("lkm", linkman);
		return "crm/lookLinkman";
	}
	/**
	 * 查询关联客户
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="getCustomerName",method = RequestMethod.GET)
	@ResponseBody
	public String getCustomerName(HttpServletRequest request,Model model){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");
		List<CrmCustomer> list = crmService.getCustomerByUserid(userid+"");
		Map<String, Object> map = new HashMap<>();
		map.put("data", list);
		JSONObject object = JSONObject.fromObject(map);
		return object.toString();
	} 
	/**
	 * 查询未归档的关联客户
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="getCustomerNameNoBracket",method = RequestMethod.GET)
	@ResponseBody
	public String getCustomerNameNoBracket(HttpServletRequest request,Model model){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");
		List<CrmCustomer> list = crmService.getCustomerByUseridNoBracket(userid+"");
		Map<String, Object> map = new HashMap<>();
		map.put("data", list);
		JSONObject object = JSONObject.fromObject(map);
		return object.toString();
	} 
	
	/**
	 * 客户交往记录列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="contactList",method = RequestMethod.GET)
	public String contactList(HttpServletRequest request,Model model){
		Integer userid =  (Integer) request.getSession().getAttribute("managerid");
		String custId = request.getParameter("custId");
		int pageSize = 10;
		request.setAttribute("custId", custId);
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		Map<String, Object> map = crmService.getContactPage(userid+"", custId, pageSize, currentPage);
		request.setAttribute("list", map.get("list"));
		request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalNum", map.get("totalNum"));
        request.setAttribute("totalPage", map.get("totalPage"));
		return "crm/contactList";
	}
	/**
	 * 根据客户id查询联系人
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="getLinkmanByCustId",method = RequestMethod.GET)
	@ResponseBody
	public String getLinkmanByCustId(HttpServletRequest request,Model model){
		String custId = request.getParameter("custId");
		List<CrmLinkman> list = crmService.getlinkmanByCustomerid(custId);
		CrmCustomer customer = crmService.getCustomerById(custId);
		Map<String, Object> map = new HashMap<>();
		map.put("data", list);
		map.put("cust", customer);
		JSONObject object = JSONObject.fromObject(map);
		return object.toString();
	}
	/**
	 * 新增客户交往记录界面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="addContact",method = RequestMethod.GET)
	public String addContact(HttpServletRequest request,Model model){
		return "crm/addContact";
	}
	/**
	 * 新增客户交往记录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="saveContact",method = RequestMethod.POST)
	@ResponseBody
	public String saveContact(HttpServletRequest request,Model model){
		String custId = request.getParameter("custId");
		//客户是否封档
		if(crmService.customerIsBracket(custId+"")){
			return "custIsBracket";
		}
		String custName = crmService.getCustomerById(custId).getCustName();
		String lkmId = request.getParameter("lkmId");
		CrmLinkman linkman = crmService.getlinkmanByid(lkmId);
		String lkmName = linkman.getLkmName();
		Integer lkmSex = linkman.getLkmSex();
		String lkmPostion = linkman.getLkmPostion();
		String lkmTel = linkman.getLkmTel();
		String lkmPhone = linkman.getLkmMobile();
 		String cttDate = request.getParameter("cttDate");
		Long cttDateLong = null;
		try {
			cttDateLong = mdf.parse(cttDate).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String cttPlace = request.getParameter("cttPlace");
		String cttTitle = request.getParameter("cttTitle");
		String cttDesc = request.getParameter("cttDesc");
		Integer userid = (Integer) request.getSession().getAttribute("managerid");
		String username = userService.getTUserById(userid+"").getName();
		CrmContact contact = new CrmContact();
		contact.setCustId(Integer.parseInt(custId));
		contact.setCustName(custName);
		contact.setLkmId(lkmId);
		contact.setLkmName(lkmName);
		contact.setLkmSex(lkmSex);
		contact.setLkmPostion(lkmPostion);
		contact.setLkmTel(lkmTel);
		contact.setLkmPhone(lkmPhone);
		contact.setCttDate(cttDateLong);
		contact.setCttPlace(cttPlace);
		contact.setCttTitle(cttTitle);
		contact.setCttDesc(cttDesc);
		contact.setUserId(userid);
		contact.setUserName(username);
		try {
			crmService.addContact(contact);
			return "addok";
		} catch (Exception e) {
			return "addno";
		}
	}
	/**
	 * 根据id查询客户交往记录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="lookContact",method = RequestMethod.GET)
	public String lookContact(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		CrmContact contact = crmService.getContactById(id);
		request.setAttribute("ctt", contact);
		return "crm/lookContact";
	}
	/**
	 * 客户封档操作
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="bracket",method = RequestMethod.POST)
	@ResponseBody
	public String bracket(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		CrmCustomer customer = new CrmCustomer();
		customer.setId(Integer.parseInt(id));
		customer.setStatus(3);
		try {
			crmService.updateCustomer(customer);
			return "ok";
		} catch (Exception e) {
			return "no";
		}
	}
	/**
	 * 客户修改类型操作
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="updateType",method = RequestMethod.POST)
	@ResponseBody
	public String updateType(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		String type = request.getParameter("type");
		CrmCustomer customer = new CrmCustomer();
		customer.setId(Integer.parseInt(id));
		customer.setType(Integer.parseInt(type));
		try {
			crmService.updateCustomer(customer);
			return "ok";
		} catch (Exception e) {
			return "no";
		}
	}
	/**
	 * 客户解封操作
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="deArchive",method = RequestMethod.POST)
	@ResponseBody
	public String deArchive(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		CrmCustomer customer = new CrmCustomer();
		customer.setId(Integer.parseInt(id));
		customer.setStatus(1);
		try {
			crmService.updateCustomer(customer);
			return "ok";
		} catch (Exception e) {
			return "no";
		}
	}
	/**
	 * 跟进记录联系人界面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="followUpByLinkman",method = RequestMethod.GET)
	public String followUpByLinkman(HttpServletRequest request,Model model){
		String linkmanid = request.getParameter("linkmanid");
		CrmLinkman linkman = crmService.getlinkmanByid(linkmanid);
		String custName = crmService.getCustomerById(linkman.getCustId()+"").getCustName();
		request.setAttribute("custName", custName);
		request.setAttribute("linkman", linkman);
		return "crm/followUpByLinkman";
	}
	/**
	 * 跟进记录客户界面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="followUpByCustomer",method = RequestMethod.GET)
	public String followUpByCustomer(HttpServletRequest request,Model model){
		String custId = request.getParameter("custId");
		String custName = crmService.getCustomerById(custId).getCustName();
		request.setAttribute("custId", custId);
		request.setAttribute("custName", custName);
		return "crm/followUpByCustomer";
	}
	/**
	 * 根据联系人id查询跟进记录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="getContactByLkmid",method = RequestMethod.GET)
	@ResponseBody
	public String getContactByLkmid(HttpServletRequest request,Model model){
		String lkmId = request.getParameter("lkmId");
		String custId = request.getParameter("custId");
		List<CrmContact> contact = new ArrayList<>();
		if(lkmId != null && !lkmId.equals("")){
			contact = crmService.getCrmContactByLkmid(lkmId);
		}else {
			contact = crmService.getContactByCust(custId);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("list", contact);
		JSONObject object = JSONObject.fromObject(map);
		return object.toString();
	}
	/**
	 * 客户界面新增客户交往记录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="saveContactByLkm",method = RequestMethod.POST)
	@ResponseBody
	public String saveContactBylkm(HttpServletRequest request,Model model){
		Map<String, Object> map = new HashMap<>();
		String custId = request.getParameter("custId");
		//客户是否封档
		if(crmService.customerIsBracket(custId+"")){
			map.put("msg", "custIsBracket");
			return JSONObject.fromObject(map).toString();
		}
		CrmContact contact = new CrmContact();
		String custName = crmService.getCustomerById(custId).getCustName();
		String lkmId = request.getParameter("lkmId");
		if(lkmId != null && !lkmId.equals("")){
			CrmLinkman linkman = crmService.getlinkmanByid(lkmId);
			String lkmName = linkman.getLkmName();
			Integer lkmSex = linkman.getLkmSex();
			String lkmPostion = linkman.getLkmPostion();
			String lkmTel = linkman.getLkmTel();
			String lkmPhone = linkman.getLkmMobile();
			contact.setLkmId(lkmId);
			contact.setLkmName(lkmName);
			contact.setLkmSex(lkmSex);
			contact.setLkmPostion(lkmPostion);
			contact.setLkmTel(lkmTel);
			contact.setLkmPhone(lkmPhone);
		}
		String cttDesc = request.getParameter("cttDesc");
		Integer userid = (Integer) request.getSession().getAttribute("managerid");
		String username = userService.getTUserById(userid+"").getName();
		contact.setCustId(Integer.parseInt(custId));
		contact.setCustName(custName);
		contact.setCttDate(new Date().getTime());
		contact.setCttDesc(cttDesc);
		contact.setUserId(userid);
		contact.setUserName(username);
		try {
			crmService.addContact(contact);
			map.put("msg", "addok");
			map.put("cttDesc", contact.getCttDesc());
			map.put("cttDateString", contact.getCttDateString());
			return JSONObject.fromObject(map).toString();
		} catch (Exception e) {
			map.put("msg", "addno");
			return JSONObject.fromObject(map).toString();
		}
	}
	/**
	 * APP查询CRM客户列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showCrmCustomerList",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String showCrmCustomerList(HttpServletRequest request,Model model){	
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
		String userid = null;
		int pageSize = 10;
		String currentPageStr=null;
		try{
			userid =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
			currentPageStr =jsonObject.getString("currentPage");
		}catch(Exception e){
            msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.SHOWCRMCUSTOMERLIST, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		// 获取当前页数
		int currentPage = 1;
		try {
			if(currentPageStr!=null && currentPageStr!=""){
				currentPage = Integer.parseInt(currentPageStr);
			}
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		Map<String, Object> map = crmService.getCustomerPage(userid, null, null, pageSize, currentPage);
		//客户数
		int custNum = ((List)map.get("list")).size(); 
		String month = formatym.format(new Date());
		//本月新增客户数
		int monthCustNum = crmService.countCustomerByMonth(userid, month);
		//本月跟进客户数
		int monthContactNum = crmService.countCustContactByMonth(userid, month);
		map.put("pageSize", pageSize);
		map.put("currentPage", currentPage);
		map.put("custNum", custNum);
		map.put("monthCustNum", monthCustNum);
		map.put("monthContactNum", monthContactNum);
		Map<String, Object> map2 = new HashMap<>();
		map2.put("code", "1");
		map2.put("data", map);
		JSONObject object = JSONObject.fromObject(map2);
		return object.toString();
	}
	/**
	 * APP查询未封档CRM客户列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showCrmCustomerListNoBracket",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String showCrmCustomerListNoBracket(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
		String userid = null;
		try{
			userid =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
		}catch(Exception e){
            msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.SHOWCRMCUSTOMERLIST, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		List<CrmCustomer> list = crmService.getCustomerByUseridNoBracket(userid);
		Map<String, Object> map = new HashMap<>();
		map.put("code", "1");
		map.put("data", list);
		JSONObject object = JSONObject.fromObject(map);
		return object.toString();
	}
	/**
	 * APP查询CRM客户详情
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showCrmCustomer",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String showCrmCustomer(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
		String userid = null;
		String custid = null;
		try{
			userid = jsonObject.getString("userid");
			custid = jsonObject.getString("custid");
//			sign =jsonObject.getString("sign");
		}catch(Exception e){
			msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
			return msg;
		}
		//判断用户信息
		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.SHOWCRMCUSTOMER, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		CrmCustomer data = crmService.getCustomerById(custid);
		Map<String, Object> map = new HashMap<>();
		map.put("username", user.getName());
		map.put("mobile", user.getMobile());
		map.put("entity", data);
		Map<String, Object> map2 = new HashMap<>();
		map2.put("code", "1");
		map2.put("data", map);
		JSONObject object = JSONObject.fromObject(map2);
		return object.toString();
	}
	/**
	 * APP查询CRM联系人列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showCrmLinkmanList",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String showCrmLinkmanList(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
//		String userid = null;
		String custid = null;
		int pageSize = 10;
		String currentPageStr=null;
		try{
//			userid =jsonObject.getString("userid");
			custid = jsonObject.getString("custid");
//			sign =jsonObject.getString("sign");
			currentPageStr =jsonObject.getString("currentPage");
		}catch(Exception e){
            msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.SHOWCRMLINKMANLIST, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		// 获取当前页数
		int currentPage = 1;
		try {
			if(currentPageStr!=null && currentPageStr!=""){
				currentPage = Integer.parseInt(currentPageStr);
			}
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		Map<String, Object> map = crmService.getlinkmanPageByCustomerid(custid, pageSize, currentPage);
		Map<String, Object> map2 = new HashMap<>();
		map2.put("code", "1");
		map2.put("data", map);
		JSONObject object = JSONObject.fromObject(map2);
		return object.toString();
	}
	/**
	 * APP查询CRM联系人详情
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showCrmLinkman",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String showCrmLinkman(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
//		String userid = null;
		String linkmanid = null;
		try{
//			userid =jsonObject.getString("userid");
			linkmanid = jsonObject.getString("linkmanid");
//			sign =jsonObject.getString("sign");
		}catch(Exception e){
            msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.SHOWCRMLINKMAN, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		CrmLinkman data = crmService.getlinkmanByid(linkmanid);
		Map<String, Object> map = new HashMap<>();
		map.put("code", "1");
		map.put("data", data);
		JSONObject object = JSONObject.fromObject(map);
		return object.toString();
	}
	/**
	 * APP新增CRM客户
	 * @param request
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "addCrmCustomer",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String addCrmCustomer(HttpServletRequest request,Model model){
//		String s = "{'userid':'41','sign':'bb5852cb81a91856ffab737b39062257','custName':'你好漂亮','custAddress':'广州市','custZip':'12345','custTel':'11111111','custWebsite':'www.baidu.com','industry':'互联网','introducer':'小李','memo':'对方水电费'}";
		String json = request.getParameter("json");
		try {
			json = new String(json.getBytes("iso8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
		String userid = null;
		String custName = null;
		String custAddress = null;
		String custZip = null;
		String custTel = null;
		String custWebsite = null;
		String industry = null;
		String introducer = null;
		String memo = null;
		try{
			userid =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
			custName =jsonObject.getString("custName");
			custAddress =jsonObject.getString("custAddress");
			custZip =jsonObject.getString("custZip");
			custTel =jsonObject.getString("custTel");
			custWebsite =jsonObject.getString("custWebsite");
			industry =jsonObject.getString("industry");
			introducer =jsonObject.getString("introducer");
			memo =jsonObject.getString("memo");
		}catch(Exception e){
			msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
			return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.ADDCRMCUSTOMER, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		//客户名是否存在
		if(crmService.customerIsNameExist(custName, userid+"", null)){
			msg="{\"code\":\"2\",\"msg\":\"客户名已经存在\"}";
			return msg;
		}
		CrmCustomer customer = new CrmCustomer();
		customer.setCustName(custName);
		customer.setCustAddress(custAddress);
		customer.setCustZip(custZip);
		customer.setCustTel(custTel);
		customer.setCustWebsite(custWebsite);
		customer.setIndustry(industry);
		customer.setIntroducer(introducer);
		customer.setMemo(memo);
		int d = Integer.parseInt(userid);
		customer.setUserId(d);
		try {
			crmService.addCustomer(customer);
			msg="{\"code\":\"1\",\"msg\":\"添加成功\"}";
		} catch (Exception e) {
			msg="{\"code\":\"2\",\"msg\":\"添加失败\"}";
		}
		return msg;
	}
	/**
	 * APP新增CRM联系人
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addCrmLinkman",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String addCrmLinkman(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
//		String userid = null;
		String custid = null;
		String lkmName = null;
		Integer lkmSex = null;
		String lkmPostion = null;
		String lkmTel = null;
		String lkmMobile = null;
		String lkmEmail = null;
		String lkmMemo = null;
		try{
//			userid =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
			custid=jsonObject.getString("custid");
			lkmName =jsonObject.getString("lkmName");
			lkmSex =jsonObject.getInt("lkmSex");
			lkmPostion =jsonObject.getString("lkmPostion");
			lkmTel =jsonObject.getString("lkmTel");
			lkmMobile =jsonObject.getString("lkmMobile");
			lkmEmail = jsonObject.getString("lkmEmail");
			lkmMemo =jsonObject.getString("lkmMemo");
		}catch(Exception e){
			msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
			return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.ADDCRMLINKMAN, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		//客户是否封档
		if(crmService.customerIsBracket(custid+"")){
			msg="{\"code\":\"2\",\"msg\":\"该客户已封档\"}";
			return msg;
		}
		CrmLinkman linkman = new CrmLinkman();
		linkman.setCustId(Integer.parseInt(custid));
		linkman.setLkmName(lkmName);
		linkman.setLkmSex(lkmSex);
		linkman.setLkmPostion(lkmPostion);
		linkman.setLkmTel(lkmTel);
		linkman.setLkmMobile(lkmMobile);
		linkman.setLkmEmail(lkmEmail);
		linkman.setLkmMemo(lkmMemo);
		try {
			crmService.addlinkman(linkman);
			msg="{\"code\":\"1\",\"msg\":\"添加成功\"}";
		} catch (Exception e) {
			msg="{\"code\":\"2\",\"msg\":\"添加失败\"}";
		}
		return msg;
	}
	/**
	 * APP CRM跟进记录列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showCrmContactList",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String showCrmContactList(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
		String userid = null;
		String linkmanid = null;
		String custid = null;
		int pageSize = 10;
		String currentPageStr=null;
		try{
			userid =jsonObject.getString("userid");
			linkmanid = jsonObject.getString("linkmanid");
//			sign =jsonObject.getString("sign");
			currentPageStr =jsonObject.getString("currentPage");
			if(linkmanid == null || linkmanid.equals("")){
				custid = jsonObject.getString("custid");
			}
		}catch(Exception e){
            msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.SHOWCRMCONTACTLIST, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		// 获取当前页数
		int currentPage = 1;
		try {
			if(currentPageStr!=null && currentPageStr!=""){
				currentPage = Integer.parseInt(currentPageStr);
			}
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		Map<String, Object> map = new HashMap<>();
		if(linkmanid != null && !linkmanid.equals("")){
			map = crmService.getCrmContactByLkmidPage(linkmanid, pageSize, currentPage);
		}else {
			map = crmService.getContactPage(userid, custid, pageSize, currentPage);
		}
		Map<String, Object> map2 = new HashMap<>();
		map2.put("code", "1");
		map2.put("data", map);
		JSONObject object = JSONObject.fromObject(map2);
		return object.toString();
	}
	/**
	 * APP CRM跟进记录详情
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showCrmContact",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String showCrmContact(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
//		String userid = null;
		String contactid = null;
		try{
//			userid =jsonObject.getString("userid");
			contactid = jsonObject.getString("contactid");
//			sign =jsonObject.getString("sign");
		}catch(Exception e){
			msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
			return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.SHOWCRMCONTACTLIST, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		CrmContact data = crmService.getContactById(contactid);
		Map<String, Object> map = new HashMap<>();
		map.put("code", "1");
		map.put("data", data);
		JSONObject object = JSONObject.fromObject(map);
		return object.toString();
	}
	/**
	 * APP新增CRM跟进记录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addCrmContact",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String addCrmContact(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
		String userid = null;
		String lkmid = null;
		String cttPlace = null;
		String cttDesc = null;
		String type = null;
		String custid = null;
		try{
			userid =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
			lkmid=jsonObject.getString("lkmid");
			cttPlace =jsonObject.getString("cttPlace");
			cttDesc =jsonObject.getString("cttDesc");
			type = jsonObject.getString("type");
			if(lkmid == null || lkmid.equals("")){
				custid = jsonObject.getString("custid");
			}
		}catch(Exception e){
			msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
			return msg;
		}
		//判断用户信息
		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.ADDCRMCONTACT, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		CrmContact contact = new CrmContact();
		if(lkmid != null && !lkmid.equals("")){
			CrmLinkman linkman = crmService.getlinkmanByid(lkmid);
			contact.setLkmId(lkmid);
			contact.setLkmName(linkman.getLkmName());
			contact.setLkmSex(linkman.getLkmSex());
			contact.setLkmPostion(linkman.getLkmPostion());
			contact.setLkmTel(linkman.getLkmTel());
			contact.setLkmPhone(linkman.getLkmPostion());
			custid = linkman.getCustId()+"";
		}
		//客户是否封档
		if(crmService.customerIsBracket(custid)){
			msg="{\"code\":\"2\",\"msg\":\"该客户已封档\"}";
			return msg;
		}
		String custName = crmService.getCustomerById(custid).getCustName();
		contact.setCustId(Integer.parseInt(custid));
		contact.setCustName(custName);
		contact.setCttDate(new Date().getTime());
		contact.setCttPlace(cttPlace);
		contact.setCttDesc(cttDesc);
		contact.setUserId(Integer.parseInt(userid));
		contact.setUserName(user.getName());
		contact.setCustType(Integer.parseInt(type));
		try {
			crmService.addContact(contact);
			//修改客户类型
			CrmCustomer customer = new CrmCustomer();
			customer.setId(Integer.parseInt(custid));
			customer.setType(Integer.parseInt(type));
			crmService.updateCustomer(customer);
			msg="{\"code\":\"1\",\"msg\":\"添加成功\"}";
		} catch (Exception e) {
			e.printStackTrace();
			msg="{\"code\":\"2\",\"msg\":\"添加失败\"}";
		}
		return msg;
	}
	/**
	 * 名片上传
	 * @param request
	 * @param model
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "uploadCard",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String upload(HttpServletRequest request,Model model,@RequestParam("file") MultipartFile file){
		String msg = null;
//		String sign = null;
		String userid = null;
		String json = request.getParameter("json");
		JSONObject jsonObject = JSONObject.fromObject(json);
		try{
//			sign =jsonObject.getString("sign");
			userid=jsonObject.getString("userid");
		}catch(Exception e){
            msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.UPLOADCARD, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		//如果文件不为空，写入上传路径
        if(!file.isEmpty()) {
        	String subpath = "card";
        	//上传文件路径
            String path = ServiceConfig.fileUploadPath+"/"+subpath+"/"+userid;
            //保存数据库路径
            String sqlPath = "upload"+"/"+subpath+"/"+userid;
            //上传文件名
            String filename = file.getOriginalFilename();
            try {
				filename = URLDecoder.decode(filename,"utf-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
            File filepath = new File(path,filename);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) { 
                filepath.getParentFile().mkdirs();
            }
            String nameCode = UUID.randomUUID().toString().replace("-", "");
            String pathFilename = path + "/" + nameCode + filename;
            String sqlPathName = sqlPath + "/" + nameCode + filename;
            //将上传文件保存到一个目标文件当中
            try {
				file.transferTo(new File(pathFilename));
			} catch (IllegalStateException e) {
				msg="{\"code\":\"2\",\"msg\":\"上传文件失败\"}";
				return msg;
			} catch (IOException e) {
				msg="{\"code\":\"2\",\"msg\":\"上传文件失败\"}";
				return msg;
			}
            //保存名片路径
            CrmUserUploadCard uploadCard = new CrmUserUploadCard();
            uploadCard.setUserId(Integer.parseInt(userid));
            uploadCard.setCardPath(sqlPathName);
            uploadCard.setUploadTime(new Date().getTime());
            crmService.addCardUpload(uploadCard);
            
            Map<String, Object> map2 = CardApiUtil.getCardImageData(pathFilename);
            int code = (int) map2.get("code");
            if(code == -1){
            	msg="{\"code\":\"2\",\"msg\":\"名片识别失败\"}";
				return msg;
            }
            //判断是否存在该公司
            String custName = (String) map2.get("custName");
            CrmCustomer customer = crmService.getCustomerByNameAndUserid(custName, userid);
            Map<String, Object> map = new HashMap<>();
            if(customer != null){
            	map2.put("oldData", customer);
            }
            map2.put("uploadPath", ServiceConfig.webServiceUrl+subpath+"/"+userid+"/"+nameCode + filename);
            map.put("code", "1");
            map.put("msg", "上传文件成功");
            map.put("data", map2);
            msg = JSONObject.fromObject(map).toString();
        } else {
        	msg="{\"code\":\"2\",\"msg\":\"上传文件失败\"}";
        }
        return msg;
	}
	/**
	 * APP根据名片新增CRM联系人
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addCrmLinkmanByCard",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String addCrmLinkmanByCard(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String msg = null;
//		String sign = null;
		String userid = null;
		String custid = null;
		String lkmName = null;
		Integer lkmSex = null;
		String lkmPostion = null;
		String lkmTel = null;
		String lkmMobile = null;
		String lkmEmail = null;
		String lkmMemo = null;
		//客户数据
		String custName = null;
		String custAddress = null;
		String custZip = null;
		String custTel = null;
		String custWebsite = null;
		String industry = null;
		String introducer = null;
		String memo = null;
		try{
			userid =jsonObject.getString("userid");
//			sign =jsonObject.getString("sign");
			custid=jsonObject.getString("custid");
			lkmName =jsonObject.getString("lkmName");
			lkmSex =jsonObject.getInt("lkmSex");
			lkmPostion =jsonObject.getString("lkmPostion");
			lkmTel =jsonObject.getString("lkmTel");
			lkmMobile =jsonObject.getString("lkmMobile");
			lkmEmail = jsonObject.getString("lkmEmail");
			lkmMemo =jsonObject.getString("lkmMemo");
			custName = jsonObject.getString("custName");
			custAddress = jsonObject.getString("custAddress");
			custZip = jsonObject.getString("custZip");
			custTel = jsonObject.getString("custTel");
			custWebsite = jsonObject.getString("custWebsite");
			industry = jsonObject.getString("industry");
			introducer = jsonObject.getString("introducer");
			memo = jsonObject.getString("memo");
		}catch(Exception e){
			msg="{\"code\":\"2\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
			return msg;
		}
		//判断用户信息
//		TUser user=userService.selectTUserId(userid);
//		if (user == null) {
//			msg="{\"code\":\"2\",\"msg\":\"用户信息有误\"}";
//			return msg;
//		}
//		boolean judge=IdentityController.authentication(user, IdentityController.ADDCRMLINKMANBYCARD, sign);
//		if(!judge){
//			msg="{\"code\":\"3\",\"msg\":\"用户身份信息有误\"}";
//			return msg;
//		}
		if(custid == null || custid .equals("")){
			if(crmService.customerIsNameExist(custName, userid, null)){
				msg="{\"code\":\"2\",\"msg\":\"公司名已存在\"}";
				return msg;
			}
			CrmCustomer customer = new CrmCustomer();
			customer.setCustName(custName);
			customer.setCustAddress(custAddress);
			customer.setCustZip(custZip);
			customer.setCustTel(custTel);
			customer.setCustWebsite(custWebsite);
			customer.setIndustry(industry);
			customer.setIntroducer(introducer);
			customer.setUserId(Integer.parseInt(userid));
			customer.setMemo(memo);
			customer.setCreateTime(new Date().getTime());
			try {
				crmService.addCustomer(customer);
			} catch (Exception e) {
				msg="{\"code\":\"2\",\"msg\":\"添加失败\"}";
				return msg;
			}
			custid = customer.getId()+"";
		}
		CrmLinkman linkman = new CrmLinkman();
		linkman.setCustId(Integer.parseInt(custid));
		linkman.setLkmName(lkmName);
		linkman.setLkmSex(lkmSex);
		linkman.setLkmPostion(lkmPostion);
		linkman.setLkmTel(lkmTel);
		linkman.setLkmMobile(lkmMobile);
		linkman.setLkmEmail(lkmEmail);
		linkman.setLkmMemo(lkmMemo);
		try {
			crmService.addlinkman(linkman);
			msg="{\"code\":\"1\",\"msg\":\"添加成功\"}";
		} catch (Exception e) {
			msg="{\"code\":\"2\",\"msg\":\"添加失败\"}";
		}
		return msg;
	}

	/**
	 * App关键字查询
	 * @param request
	 * @param model
	 * @return
	 */
	/*@RequestMapping(value="selectByKeyword",method=RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String search(HttpServletRequest request,Model model){
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(json);
		String keyword = null;
		String userid = null;
		keyword = jsonObject.getString("keyword");
		userid = jsonObject.getString("userid");
		Map<String, Object> map = crmService.selectByKeyword(keyword);
		//客户数
		int custNum = ((List)map.get("list")).size(); 
		String month = formatym.format(new Date());
		//本月新增客户数
		int monthCustNum = crmService.countCustomerByMonth(userid, month);
		//本月跟进客户数
		int monthContactNum = crmService.countCustContactByMonth(userid, month);
		map.put("custNum", custNum);
		map.put("monthCustNum", monthCustNum);
		map.put("monthContactNum", monthContactNum);
		Map<String, Object> map2 = new HashMap<>();
		map2.put("code", "1");
		map2.put("data", map);
		JSONObject object = JSONObject.fromObject(map2);
		//TODO
		return object.toString();
	}*/
	
	
	//导出用户信息
		@RequestMapping("export")  
		public void exportInof(HttpServletRequest request,HttpServletResponse response) throws Exception{  
		    response.setContentType("application/vnd.ms-excel");  
		    String filename="客户报表.xls";
		    filename = new String(filename.getBytes(), "ISO-8859-1");
		    response.setHeader("Content-Disposition", "attachment; filename="+filename);  
		    OutputStream out = response.getOutputStream();  
		    String name = request.getParameter("name");
		    String type = request.getParameter("type");
			int pageSize = 10;
			try {
				if (name!=null&&name.length() > 0) {
					name = URLDecoder.decode(URLDecoder.decode(name, "UTF-8"),"UTF-8");
				}
			} catch (UnsupportedEncodingException e) {
			}
			// 获取当前页数
			int currentPage = 1;
			try {
				currentPage = new Integer(request.getParameter("currentPage"));
			} catch (Exception e) {
			}
			currentPage = currentPage <= 0 ? 1 : currentPage;
			Integer userid= (Integer) request.getSession().getAttribute("managerid");
			Map<String,Object> map=crmService.getCustomerPage(userid.toString(),name, type, pageSize,currentPage);
			List<CrmCustomer> list = (List<CrmCustomer>) map.get("list");
			List<CrmCustomer> replist=new ArrayList<CrmCustomer>();
			for (CrmCustomer att : list) {
				CrmCustomer rep=new CrmCustomer();
				rep.setCustName(att.getCustName());
				rep.setCustAddress(att.getCustAddress());
				rep.setCustTel(att.getCustTel());
				rep.setCustWebsite(att.getCustWebsite());
				rep.setCustZip(att.getCustZip());
				rep.setIndustry(att.getIndustry());
				rep.setIntroducer(att.getIntroducer());
				rep.setMemo(att.getMemo());
				replist.add(rep);
			}
			ExcelUtil<CrmCustomer> t=new ExcelUtil<CrmCustomer>();
			String [] headers={"","公司名","地址","邮政编码","电话","网址","所属行业","推荐人","备注"};  
			t.exportExcel("sheet名称", headers, replist, out, "yyyy-MM-dd HH:mm:ss");
			}
	
}
